import React, { FC, useState } from 'react'
import { NavBar, Space, Toast, Form, Input, Button, Picker } from 'antd-mobile'
import { reg } from '../utils/validate'
import { useCountDown } from 'ahooks'

import { captchaSent } from '../api/api'
import { ShowErrorMsg, ShowSuccessMsg } from '../utils/message'

const CaptchaBtn: FC<any> = ({
  name,
  phone
}) => {
  const [toggle, setToggle] = useState<boolean>(true)
  const total = 60

  const startSendCaptcha = async () => {
    const res: any = await captchaSent({
      phone
    })
    if (res.code == 200) {
      setToggle(false)
      setTargetDate(Date.now() + total * 1000)
      ShowSuccessMsg('发送成功')
    } else {
      ShowErrorMsg('发送失败')
    }
  }


  // 验证码发送倒计时
  const [targetDate, setTargetDate] = useState<number>()
  const [count] = useCountDown({
    targetDate,
    interval: 1000,
    onEnd: () => {
      setToggle(true)
    }
  })

  return (
    <Form.Item
      label='验证码：'
      name={name}
      extra={
        toggle ? <Button onClick={startSendCaptcha} color='warning' size='mini' disabled={!reg.phone.test(phone)}>发送验证码</Button> :
          <span>剩余 {Math.round(count / 1000)}s</span>
      }
      rules={[
        { required: true, message: '验证码不能为空' },
        { pattern: reg.code, message: '验证码格式不正确' }
      ]}
    >
      <Input placeholder='请输入验证码' clearable />
    </Form.Item>
  )
}

CaptchaBtn.defaultProps = {
  name: 'captcha'
}

export default CaptchaBtn
